﻿using System;
using System.Data;
// IBM
using IBM.Data.DB2.iSeries;
using System.Globalization;

namespace Prassi2ExpertUpTransfer
{
    public sealed class ConnettiPrassiDB
    {
        static ConnettiPrassiDB instanza = null;


        CultureInfo ci = null;

        iDB2Connection connessione = null;



        private ConnettiPrassiDB()
        {
            connessione = new iDB2Connection(
            "Data Source=10.3.2.2; " +
            "User ID=PRDANIELE; " +
            "Password=DANIELEPR; " +
            "ConnectionTimeout=60; " +
            "DataCompression=True; "         
                );

            ci = new CultureInfo("it-IT");
        }

        public static ConnettiPrassiDB Instanza
        {
            get
            {
                if (instanza == null) instanza = new ConnettiPrassiDB();
                return instanza;
            }
        }

        public iDB2Connection GetDBConnection()
        {
            if (connessione.State != ConnectionState.Open)
            {
                connessione.Open();
            }
            return connessione;
        }

        public void CloseConnection()
        {
            if (connessione.State == ConnectionState.Open)
            {
                connessione.Close();
            }
        }

        
        public string getValue(string column, string table, string where)
        {

            string valore = null;
            string cmd_sql = "select " + column + " from " + table + " " + where;
            try
            {
                iDB2Connection myConnection = GetDBConnection();

                iDB2Command myCommand = new iDB2Command(cmd_sql, myConnection);

                valore = Convert.ToString(myCommand.ExecuteScalar());


            }
            catch (Exception err)
            {
                // TODO Exception AccessoDBException
                throw new Eccezioni.AccessoDBException(cmd_sql, err);
            }

            return valore;
        }

        public int getValueInt(string column, string table, string where)
        {

            int valore = 0;
            try
            {
                Int32.TryParse(getValue(column, table, where), out valore);
            }
            catch (Exception err)
            {
                // TODO Exception rilanciata
                throw err;
            }

            return valore;
        }
    }
}